package com.supinfo.food.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import com.supinfo.food.dao.MagasinDao;
import com.supinfo.food.entities.Magasin;

/**
 * Magasin DAO
 * @author Keitaro
 */
public class JpaMagasinDao implements MagasinDao {

	/** Entity manager */
	private EntityManager entityManager;

	public JpaMagasinDao() {
		entityManager = ManagerDAO.getEntityManager();
	}
	
	@Override
	public Magasin get(Long id) {
		try {
			return entityManager.find(Magasin.class, id);
		} catch (NoResultException e) {
			return null;
		}
	}

	@Override
	public void remove(Long id) {
		Magasin magasin = get(id);
		if (magasin != null) {
			entityManager.getTransaction().begin();
			entityManager.remove(magasin);
			entityManager.getTransaction().commit();
		}
	}

	@Override
	public Magasin persist(Magasin magasin) {
		entityManager.getTransaction().begin();
		entityManager.persist(magasin);
		entityManager.getTransaction().commit();
		return magasin;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Magasin> getAll() {
		return entityManager.createQuery("SELECT m FROM Magasin m").getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<String> getCountries() {
		return entityManager.createQuery("SELECT m.location FROM Magasin m GROUP BY m.location").getResultList();
	}

}
